<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="总结Vue3 Composition API风格下定义Props的七种方式">
<meta property="og:type" content="article">
<meta property="og:title" content="TS定义组件Props的default和required">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/vue3_practice/TS%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6Props%E7%9A%84default%E5%92%8Crequired/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="总结Vue3 Composition API风格下定义Props的七种方式">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-02-02T15:00:12.000Z">
<meta property="article:modified_time" content="2023-02-24T14:19:59.513Z">
<meta property="article:author" content="William Leung">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/vue3_practice/TS%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6Props%E7%9A%84default%E5%92%8Crequired/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>TS定义组件Props的default和required | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%90%E8%A1%8C%E6%97%B6%E5%A3%B0%E6%98%8E"><span class="nav-number">1.</span> <span class="nav-text">运行时声明</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-defineProps-%E6%95%B0%E7%BB%84%E7%9A%84%E9%85%8D%E7%BD%AE%E6%96%B9%E5%BC%8F"><span class="nav-number">1.1.</span> <span class="nav-text">1. defineProps()数组的配置方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-defineProps-%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%AE%80%E5%8D%95%E9%85%8D%E7%BD%AE%E6%96%B9%E5%BC%8F"><span class="nav-number">1.2.</span> <span class="nav-text">2. defineProps()对象的简单配置方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-defineProps-%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%AF%A6%E7%BB%86%E9%85%8D%E7%BD%AE%E6%96%B9%E5%BC%8F"><span class="nav-number">1.3.</span> <span class="nav-text">3. defineProps()对象的详细配置方式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#TS%E7%B1%BB%E5%9E%8B%E5%A3%B0%E6%98%8E"><span class="nav-number">2.</span> <span class="nav-text">TS类型声明</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-defineProps-lt-%E6%B3%9B%E5%9E%8B%E5%8F%82%E6%95%B0-gt-%E7%9A%84%E6%96%B9%E5%BC%8F"><span class="nav-number">2.1.</span> <span class="nav-text">1. defineProps&lt;泛型参数&gt;()的方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-withDefaults-defineProps-lt-%E6%B3%9B%E5%9E%8B%E5%8F%82%E6%95%B0-gt-%E7%9A%84%E6%96%B9%E5%BC%8F"><span class="nav-number">2.2.</span> <span class="nav-text">2. withDefaults+defineProps&lt;泛型参数&gt;()的方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-PropType%E7%9A%84%E6%96%B9%E5%BC%8F"><span class="nav-number">2.3.</span> <span class="nav-text">3. PropType的方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-PropType-ExtractPropTypes%E7%9A%84%E6%96%B9%E5%BC%8F"><span class="nav-number">2.4.</span> <span class="nav-text">4. PropType+ExtractPropTypes的方式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8A%A8%E6%80%81%E7%BB%84%E4%BB%B6%E5%A6%82%E4%BD%95%E6%A0%B9%E6%8D%AEProps%E8%BF%87%E6%BB%A4v-bind%E7%BB%91%E5%AE%9A%E7%9A%84%E5%B1%9E%E6%80%A7%EF%BC%9F"><span class="nav-number">3.</span> <span class="nav-text">动态组件如何根据Props过滤v-bind绑定的属性？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%A4%BA%E4%BE%8B%E9%A1%B9%E7%9B%AE"><span class="nav-number">4.</span> <span class="nav-text">示例项目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number">5.</span> <span class="nav-text">参考</span></a></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/vue3_practice/TS%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6Props%E7%9A%84default%E5%92%8Crequired/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          TS定义组件Props的default和required
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-02-02 23:00:12" itemprop="dateCreated datePublished" datetime="2023-02-02T23:00:12+08:00">2023-02-02</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2023-02-24 22:19:59" itemprop="dateModified" datetime="2023-02-24T22:19:59+08:00">2023-02-24</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/Vue3%E9%87%87%E5%9D%91%E5%AE%9E%E8%B7%B5/" itemprop="url" rel="index"><span itemprop="name">Vue3采坑实践</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.7k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>5 分钟</span>
    </span>
</div>

            <div class="post-description">总结Vue3 Composition API风格下定义Props的七种方式</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>Composition API风格代码下，Vue组件声明Props有两种方式： <strong>运行时声明</strong> 、 <strong>TS类型声明</strong> 。两者是互斥的，不能在代码中混用。</p>
<p><strong>“运行时声明(runtime declaration)”</strong> ，是说当props传值有误时，主要表现为在浏览器控制台报warning错误，VSCode/Webstorm是无法提前检测的。而错误一旦发生在生产环境，势必会增加问题的复现难度、定位难度，以及修复难度。</p>
<p><strong>“类型声明(type declaration)”</strong> ，由于TypeScript是静态类型语言，当props传值有误时控制台也会报错，但同时VSCode会对该代码片段标红，并提示相关错误的信息，就能帮助我们提前发现问题，对程序设计更有掌控力。</p>
<p>本文通过一个<code>DataNumber</code>组件，对props的定义方式进行说明。</p>
<h2 id="运行时声明"><a href="#运行时声明" class="headerlink" title="运行时声明"></a>运行时声明</h2><h3 id="1-defineProps-数组的配置方式"><a href="#1-defineProps-数组的配置方式" class="headerlink" title="1. defineProps()数组的配置方式"></a>1. <code>defineProps()</code>数组的配置方式</h3><p>由于<code>defineProps()</code>是编译器宏函数，所以不需要手动<code>import</code>导入，可以直接使用</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">setup</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="comment">// 最简单的方式：defineProps函数传递一个或多个propsName</span></span></span><br><span class="line"><span class="javascript"><span class="keyword">const</span> props = defineProps([<span class="string">&quot;position&quot;</span>, <span class="string">&quot;options&quot;</span>, <span class="string">&quot;data&quot;</span>]);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="2-defineProps-对象的简单配置方式"><a href="#2-defineProps-对象的简单配置方式" class="headerlink" title="2. defineProps()对象的简单配置方式"></a>2. <code>defineProps()</code>对象的简单配置方式</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">setup</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="comment">// defineProps传递的是配置对象，propName为key，数据类型为value</span></span></span><br><span class="line">defineProps(&#123;</span><br><span class="line"><span class="javascript">  data: [<span class="built_in">String</span>, <span class="built_in">Number</span>],</span></span><br><span class="line"><span class="javascript">  position: <span class="built_in">Object</span>,</span></span><br><span class="line"><span class="javascript">  options: <span class="built_in">Object</span>,</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="3-defineProps-对象的详细配置方式"><a href="#3-defineProps-对象的详细配置方式" class="headerlink" title="3. defineProps()对象的详细配置方式"></a>3. <code>defineProps()</code>对象的详细配置方式</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">setup</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="comment">// propName为key，但propValue是更详细的设置，支持type/required/default/validator等属性配置</span></span></span><br><span class="line">defineProps(&#123;</span><br><span class="line">  data: &#123;</span><br><span class="line"><span class="javascript">    type: [<span class="built_in">String</span>, <span class="built_in">Number</span>],</span></span><br><span class="line"><span class="javascript">    <span class="keyword">default</span>: <span class="string">&quot;--&quot;</span>,</span></span><br><span class="line">  &#125;,</span><br><span class="line">  position: &#123;</span><br><span class="line"><span class="javascript">    type: <span class="built_in">Object</span>,</span></span><br><span class="line"><span class="javascript">    required: <span class="literal">false</span>,</span></span><br><span class="line"><span class="javascript">    <span class="keyword">default</span>: &#123;</span></span><br><span class="line">      top: 0,</span><br><span class="line">      left: 0,</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  options: &#123;</span><br><span class="line"><span class="javascript">    type: <span class="built_in">Object</span>,</span></span><br><span class="line"><span class="javascript">    required: <span class="literal">false</span>,</span></span><br><span class="line"><span class="javascript">    <span class="keyword">default</span>: &#123;</span></span><br><span class="line"><span class="javascript">      animate: <span class="literal">false</span>,</span></span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;);</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="TS类型声明"><a href="#TS类型声明" class="headerlink" title="TS类型声明"></a>TS类型声明</h2><p>Vue3中使用TypeScript，先把组件中的类型定义给出来</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 排列方向-枚举类型</span></span><br><span class="line">enum DirectionEnum &#123;</span><br><span class="line">  horizontal = <span class="string">&quot;HORIZONTAL&quot;</span>,</span><br><span class="line">  vertical = <span class="string">&quot;VERTICAL&quot;</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定位信息</span></span><br><span class="line">type Position = &#123;</span><br><span class="line">  top: string | number;</span><br><span class="line">  left: string | number;</span><br><span class="line">  zIndex: number;</span><br><span class="line">  width?: string | number;</span><br><span class="line">  height?: string | number;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 详细配置信息</span></span><br><span class="line">type DataNumberOptionsType = &#123;</span><br><span class="line">  animate?: boolean;</span><br><span class="line">  thousandsCharacter?: boolean;</span><br><span class="line">  direction: DirectionEnum;</span><br><span class="line">  label: string;</span><br><span class="line">  suffix: string;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 组件最终的数据类型</span></span><br><span class="line">interface DataNumberType &#123;</span><br><span class="line">  data: string | number;</span><br><span class="line">  position?: Position;</span><br><span class="line">  options?: DataNumberOptionsType;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里值得注意的是，<code>DataNumberType</code>中的结构定义，如果不加<code>?</code>则是必填的，有了<code>?</code>相当于<code>required=false</code></p>
<h3 id="1-defineProps-lt-泛型参数-gt-的方式"><a href="#1-defineProps-lt-泛型参数-gt-的方式" class="headerlink" title="1. defineProps&lt;泛型参数&gt;()的方式"></a>1. <code>defineProps&lt;泛型参数&gt;()</code>的方式</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">setup</span> <span class="attr">lang</span>=<span class="string">&quot;ts&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript"><span class="comment">// 忽略上述的类型定义声明</span></span></span><br><span class="line"></span><br><span class="line"><span class="javascript"><span class="comment">// 通过泛型参数的方式进行props定义</span></span></span><br><span class="line"><span class="handlebars"><span class="xml">defineProps<span class="tag">&lt;<span class="name">DataNumberType</span>&gt;</span>();</span></span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>这种方式，好在将“运行时声明”改成TS静态的类型声明，但缺点就是没办法设置默认值。</p>
<h3 id="2-withDefaults-defineProps-lt-泛型参数-gt-的方式"><a href="#2-withDefaults-defineProps-lt-泛型参数-gt-的方式" class="headerlink" title="2. withDefaults+defineProps&lt;泛型参数&gt;()的方式"></a>2. <code>withDefaults</code>+<code>defineProps&lt;泛型参数&gt;()</code>的方式</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 忽略上述的类型定义声明</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// withDefaults()也是宏函数</span></span><br><span class="line"><span class="comment">// 第一个参数是defineProps函数调用，第二个参数是配置默认值</span></span><br><span class="line">withDefaults(defineProps&lt;DataNumberType&gt;(), &#123;</span><br><span class="line">  <span class="comment">// 基础数据类型，直接赋值</span></span><br><span class="line">  data: <span class="string">&quot;--&quot;</span>, </span><br><span class="line">  <span class="comment">// 复杂数据类型，需要通过一个箭头函数return出来</span></span><br><span class="line">  position: <span class="function">() =&gt;</span> (&#123;</span><br><span class="line">    left: <span class="number">0</span>,</span><br><span class="line">    top: <span class="number">0</span>,</span><br><span class="line">    zIndex: <span class="number">0</span>,</span><br><span class="line">  &#125;),</span><br><span class="line">  options: <span class="function">() =&gt;</span> (&#123;</span><br><span class="line">    animate: <span class="literal">true</span>,</span><br><span class="line">    thousandsCharacter: <span class="literal">true</span>,</span><br><span class="line">    direction: DirectionEnum.horizontal,</span><br><span class="line">    label: <span class="string">&quot;订单&quot;</span>,</span><br><span class="line">    suffix: <span class="string">&quot;笔&quot;</span>,</span><br><span class="line">  &#125;),</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>通过<code>withDefaults()</code>可以进行类型声明，也可以设置是否必填，还能设置默认值。但如果需要配置<code>props.validator</code>校验，就没办法了。</p>
<h3 id="3-PropType的方式"><a href="#3-PropType的方式" class="headerlink" title="3. PropType的方式"></a>3. <code>PropType</code>的方式</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// PropsType需要提前引入</span></span><br><span class="line"><span class="keyword">import</span> &#123; type PropType &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 忽略上述一大段的类型声明</span></span><br><span class="line"></span><br><span class="line">defineProps(&#123;</span><br><span class="line">  data: &#123;</span><br><span class="line">    type: [<span class="built_in">String</span>, <span class="built_in">Number</span>],</span><br><span class="line">    <span class="keyword">default</span>: <span class="string">&#x27;--&#x27;</span>,</span><br><span class="line">    <span class="function"><span class="title">validaor</span>(<span class="params">value: string</span>)</span> &#123;</span><br><span class="line">      <span class="keyword">if</span>(value === <span class="string">&#x27;暂无数据&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  position: &#123;</span><br><span class="line">    type: <span class="built_in">Object</span> <span class="keyword">as</span> PropType&lt;Position&gt;,</span><br><span class="line">    required: <span class="literal">false</span>,</span><br><span class="line">    deault: &#123;</span><br><span class="line">      left: <span class="number">0</span>,</span><br><span class="line">      top: <span class="number">0</span>,</span><br><span class="line">      zIndex: <span class="number">0</span>,</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  options: &#123;</span><br><span class="line">    type: <span class="built_in">Object</span> <span class="keyword">as</span> PropType&lt;DataNumberOptionsType&gt;,</span><br><span class="line">    <span class="built_in">require</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="keyword">default</span>: &#123;</span><br><span class="line">      animate: <span class="literal">false</span>,</span><br><span class="line">      thousandsCharacter: <span class="literal">false</span>,</span><br><span class="line">      direction: <span class="string">&quot;horizontal&quot;</span>,</span><br><span class="line">      label: <span class="string">&quot;待入馆&quot;</span>,</span><br><span class="line">      suffix: <span class="string">&quot;人&quot;</span>,</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>这样既能利用TS的类型声明，又能完整的使用<code>Props</code>的配置功能。</p>
<p>但仍然不完美，类型声明代码太多了，能不能抽取到独立文件，从外部文件引入呢？</p>
<p>Vue官方文档给出了解释： <strong>“因为 Vue 组件是单独编译的，编译器目前不会抓取导入的文件以分析源类型。计划在未来的版本中解决这个限制。”</strong> </p>
<h3 id="4-PropType-ExtractPropTypes的方式"><a href="#4-PropType-ExtractPropTypes的方式" class="headerlink" title="4. PropType+ExtractPropTypes的方式"></a>4. <code>PropType</code>+<code>ExtractPropTypes</code>的方式</h3><p>我们先把类型声明放到<code>DataNumber.d.ts</code>文件，然后通过<code>ExtractPropTypes</code>进行导出</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ExtractPropTypes需要提前引入</span></span><br><span class="line"><span class="keyword">import</span> &#123; ExtractPropTypes &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">enum</span> DirectionEnum &#123;</span><br><span class="line">  horizontal = <span class="string">&#x27;HORIZONTAL&#x27;</span>,</span><br><span class="line">  vertical = <span class="string">&#x27;VERTICAL&#x27;</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Position = &#123;</span><br><span class="line">  top: <span class="built_in">string</span> | <span class="built_in">number</span>;</span><br><span class="line">  left: <span class="built_in">string</span> | <span class="built_in">number</span>;</span><br><span class="line">  zIndex: <span class="built_in">number</span>;</span><br><span class="line">  width?: <span class="built_in">string</span> | <span class="built_in">number</span>;</span><br><span class="line">  height?: <span class="built_in">string</span> | <span class="built_in">number</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> DataNumberOptionsType = &#123;</span><br><span class="line">  animate?: <span class="built_in">boolean</span>;</span><br><span class="line">  thousandsCharacter?: <span class="built_in">boolean</span>;</span><br><span class="line">  direction: DirectionEnum;</span><br><span class="line">  label: <span class="built_in">string</span>;</span><br><span class="line">  suffix: <span class="built_in">string</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// export暴露出去</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">type</span> Position = ExtractPropTypes&lt;<span class="keyword">typeof</span> Position&gt;;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">type</span> DataNumberOptionsType = ExtractPropTypes&lt;</span><br><span class="line">  <span class="keyword">typeof</span> DataNumberOptionsType</span><br><span class="line">&gt;;</span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">setup</span> <span class="attr">lang</span>=<span class="string">&quot;ts&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">import</span> &#123; type PropType &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span>;</span></span><br><span class="line"><span class="javascript"><span class="comment">// 使用的时候，从类型文件引入</span></span></span><br><span class="line"><span class="javascript"><span class="keyword">import</span> &#123; Position, DataNumberOptionsType &#125; <span class="keyword">from</span> <span class="string">&#x27;./DataNumber.d&#x27;</span></span></span><br><span class="line"></span><br><span class="line">defineProps(&#123;</span><br><span class="line">  data: &#123;</span><br><span class="line"><span class="javascript">    type: [<span class="built_in">String</span>, <span class="built_in">Number</span>],</span></span><br><span class="line"><span class="javascript">    <span class="keyword">default</span>: <span class="string">&#x27;--&#x27;</span>,</span></span><br><span class="line"><span class="javascript">    <span class="function"><span class="title">validaor</span>(<span class="params">value: string</span>)</span> &#123;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">if</span> (value === <span class="string">&#x27;暂无数据&#x27;</span>) &#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> <span class="literal">false</span></span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  position: &#123;</span><br><span class="line"><span class="javascript">    type: <span class="built_in">Object</span> <span class="keyword">as</span> PropType&lt;Position&gt;,</span></span><br><span class="line"><span class="javascript">    required: <span class="literal">false</span>,</span></span><br><span class="line">    deault: &#123;</span><br><span class="line">      left: 0,</span><br><span class="line">      top: 0,</span><br><span class="line">      zIndex: 0,</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  options: &#123;</span><br><span class="line"><span class="javascript">    type: <span class="built_in">Object</span> <span class="keyword">as</span> PropType&lt;DataNumberOptionsType&gt;,</span></span><br><span class="line"><span class="javascript">    <span class="built_in">require</span>: <span class="literal">true</span>,</span></span><br><span class="line"><span class="javascript">    <span class="keyword">default</span>: &#123;</span></span><br><span class="line"><span class="javascript">      animate: <span class="literal">false</span>,</span></span><br><span class="line"><span class="javascript">      thousandsCharacter: <span class="literal">false</span>,</span></span><br><span class="line"><span class="javascript">      direction: <span class="string">&quot;horizontal&quot;</span>,</span></span><br><span class="line"><span class="javascript">      label: <span class="string">&quot;待入馆&quot;</span>,</span></span><br><span class="line"><span class="javascript">      suffix: <span class="string">&quot;人&quot;</span>,</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>


<h2 id="动态组件如何根据Props过滤v-bind绑定的属性？"><a href="#动态组件如何根据Props过滤v-bind绑定的属性？" class="headerlink" title="动态组件如何根据Props过滤v-bind绑定的属性？"></a>动态组件如何根据Props过滤<code>v-bind</code>绑定的属性？</h2><p>如上述案例，还有个新问题：<code>v-bind</code>绑定<code>config</code>到组件上，把<code>sid</code>和<code>component</code>属性也绑进去了，只是转换成<code>attribute</code>到DOM元素上。</p>
<p>那怎么能动态过滤呢？只有符合组件Props的key才绑定进去，不符合的抛弃</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  &lt;component</span><br><span class="line">    :is=&quot;componentMap[config.component]&quot;</span><br><span class="line">    v-bind=&quot;calcPropsBindData(config.component, config)&quot;</span><br><span class="line">  &gt;<span class="tag">&lt;/<span class="name">component</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">import</span> DataNumber <span class="keyword">from</span> <span class="string">&quot;./DataNumber.vue&quot;</span>;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript"><span class="keyword">const</span> componentMap = &#123;</span></span><br><span class="line">  DataNumber,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="javascript"><span class="comment">// 引入的DataNumber是组件类，可读取到props的定义对象</span></span></span><br><span class="line"><span class="javascript"><span class="comment">// 根据组件props的key过滤config，再返回</span></span></span><br><span class="line"><span class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">calcPropsBindData</span>(<span class="params">config</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">const</span> &#123; component &#125; = config;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">const</span> &#123; props &#125; = componentMap[component];</span></span><br><span class="line"><span class="javascript">  <span class="keyword">const</span> propKeys = <span class="built_in">Object</span>.keys(props);</span></span><br><span class="line"><span class="javascript">  <span class="keyword">const</span> result = &#123;&#125;;</span></span><br><span class="line"><span class="javascript">  propKeys.map(<span class="function">(<span class="params">key</span>) =&gt;</span> &#123;</span></span><br><span class="line">    result[key] = config[key];</span><br><span class="line">  &#125;);</span><br><span class="line"><span class="javascript">  <span class="keyword">return</span> result;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="示例项目"><a href="#示例项目" class="headerlink" title="示例项目"></a>示例项目</h2><p><a href="https://gitee.com/lianghuilin/demo-tsdefine-components-props">https://gitee.com/lianghuilin/demo-tsdefine-components-props</a></p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a target="_blank" rel="noopener" href="https://cn.vuejs.org/guide/components/props.html">Vue文档-Props声明</a></li>
<li><a target="_blank" rel="noopener" href="https://cn.vuejs.org/guide/typescript/composition-api.html#typing-component-props">Vue文档-为组件的 props 标注类型</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/vue3_practice/TS%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6Props%E7%9A%84default%E5%92%8Crequired/" title="TS定义组件Props的default和required">https://gitee.com/lianghuilin/murmur.git/vue3_practice/TS定义组件Props的default和required/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/crush_notes/vue-echarts%E9%85%8D%E7%BD%AEmarkLine%E7%9A%84%E4%B8%80%E4%BA%9B%E7%8A%B6%E5%86%B5/" rel="prev" title="vue-echarts配置markLine的一些状况">
                  <i class="fa fa-chevron-left"></i> vue-echarts配置markLine的一些状况
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/crush_notes/%E6%8E%8C%E6%8F%A1%E4%B8%8E%E4%BD%BF%E7%94%A8Vue%E6%8C%87%E4%BB%A4/" rel="next" title="掌握与使用Vue指令">
                  掌握与使用Vue指令 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
